package com.ljh.mall.service.Impl;

import com.ljh.mall.mybatis.mapper.UmsAdminDao;
import com.ljh.mall.mybatis.model.UmsAdmin;
import com.ljh.mall.mybatis.result.CodeMsg;
import com.ljh.mall.mybatis.result.Result;
import com.ljh.mall.mybatis.util.MD5Util;
import com.ljh.mall.service.AdminService;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private UmsAdminDao umsAdminDao;

    @Override
    public UmsAdmin login(UmsAdmin umsAdmin) {
        return umsAdminDao.selectByUsernameAndPassword(umsAdmin);
    }


    @Override
    public Result<UmsAdmin> loginByMD5(UmsAdmin umsAdmin) {
        UmsAdmin admin = this.umsAdminDao.selectByUsername(umsAdmin);
        if(ObjectUtils.isEmpty(admin)) {
            return Result.error(CodeMsg.USERNAME_PASSWORD_ERROR);
        }

        String dbPwd = admin.getPassword();
        String saltDB = admin.getSalt();

        String calaPass = MD5Util.inputPassToDbPass(umsAdmin.getPassword(), saltDB);
        if(!StringUtils.equals(dbPwd, calaPass)) { // 密码不一致
            return Result.error(CodeMsg.PASSWORD_ERROR);
        }
        // 返回的admin信息中不能有密码的信息，所以要将密码置空
        admin.setPassword(StringUtils.EMPTY);

        return Result.success(admin);
    }

    @Override
    public int register(UmsAdmin umsAdmin) {
        return umsAdminDao.insertSelective(umsAdmin);
    }


}
